package com.eu.ebpm.engine.cmd.pvm;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eu.ebpm.engine.cmd.TaskIdentitySupport;
import com.eu.ebpm.engine.entity.deploy.Mission;
import com.eu.ebpm.engine.entity.deploy.Transfer;
import com.eu.ebpm.engine.entity.enumm.TaskStatus;
import com.eu.ebpm.engine.entity.history.HisTask;
import com.eu.ebpm.engine.entity.runtime.TaskEntity;
import com.eu.ebpm.engine.repository.HisTaskRepository;
import com.eu.ebpm.engine.repository.TaskRepository;
import com.eu.ebpm.engine.script.SpelScriptService;
import org.springframework.util.StringUtils;

/**
 * 
 * @author wxh
 */
@Component
public class LaneBeforeIntoCommand {

	@Autowired
	protected TaskIdentitySupport taskIdentityService;
	@Autowired
	private HisTaskRepository hisTaskRepository;
	@Autowired
	private TaskRepository taskRepository;
	@Autowired
	private SpelScriptService spelScriptService;
	
	public void execute(Mission laneBeforeMission, TaskEntity task, Map<String, Object> variables) {
		Transfer nextTransfer = laneBeforeMission.getTransfers().get(0);
		Mission next = nextTransfer.getToMission();
		
		//记录laneBefore的执行记录
		HisTask hisTask = new HisTask(laneBeforeMission.getType(), laneBeforeMission.getName(), laneBeforeMission.getDesc(), nextTransfer.getName(), task.getExecutionId(), task.getRootExecutionId(), laneBeforeMission.getId(), null, null, new Date(), new Date());
		hisTaskRepository.insert(hisTask);

		/**
		 * 这里需要拿到 laneTask,根据laneTask插入一条语句以后,在插入IdentityService
		 * 这里需要注意,只有第一条 laneTask 需要[用户]或[角色]或[机构]认领
		 */
		TaskEntity laneTask = new TaskEntity(next.getName(), next.getDesc(), new Date(), task.getExecutionId(), task.getRootExecutionId(), next.getId());
		if(!StringUtils.isEmpty(laneBeforeMission.getAssignee())) {
			spelScriptService.initAssignee(laneBeforeMission, laneTask);
			laneTask.setAssigneeTime(new Date());
		} else {
			taskIdentityService.insertTaskCandidate(laneBeforeMission, laneTask);
		}
		
		taskRepository.insert(laneTask);
		
		hisTaskRepository.insert(new HisTask(laneTask.getId(), next.getType(), next.getName(), next.getDesc(), null, task.getExecutionId(), task.getRootExecutionId(), laneTask.getMissionId(), laneTask.getAssignee(), laneTask
				.getAssigneeTime(), laneTask.getCreateTime(), null, null, TaskStatus.EXEING.getCode()));
		
	}
	
	
	
	
	

}
